<template>
  <div class="post-detail">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ post.postTitle }}</span>
      </div>
      <div class="post-content" v-html="post.postContent"></div>
    </el-card>
    <el-card class="comments-section" v-if="comments.length > 0">
      <div slot="header" class="clearfix">
        <span>评论 ({{ comments.length }})</span>
      </div>
      <div class="comment-list">
        <div
          class="comment"
          v-for="comment in comments"
          :key="comment.commentId"
        >
          <el-avatar :src="avatar" :size="40" shape="square"></el-avatar>
          <div class="comment-detail">
            <div class="comment-header">
              <span class="comment-user">{{ comment.userName }}</span>
              <span class="comment-time">{{ comment.createdAt }}</span>
              <el-button
                v-if="comment.userId === currentUserId"
                type="text"
                icon="el-icon-delete"
                @click.stop="deleteComment(comment.commentId)"
              >删除</el-button>
            </div>
            <div class="comment-content">{{ comment.commentContent }}</div>
          </div>
        </div>
      </div>
    </el-card>
    <el-input
      type="textarea"
      placeholder="添加评论..."
      v-model="newComment"
      class="comment-input"
      style="margin-bottom: 20px"
    ></el-input>
    <el-button type="primary" @click="submitComment">评论</el-button>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  listPosts,
  getPosts,
  delPosts,
  addPosts,
  updatePosts,
} from "@/api/teahouse/posts";
import {
  listComments,
  getComments,
  delComments,
  addComments,
  updateComments,
} from "@/api/teahouse/comments";

export default {
  name: "PostDetail",
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      post: {},
      comments: [],
      newComment: "",
      currentUserId: this.$store.state.user.id,
    };
  },
  mounted() {
    this.fetchPostAndComments();
  },
  methods: {
    toggleLike() {
      this.post.liked = !this.post.liked;
      this.post.likes += this.post.liked ? 1 : -1;
    },
    fetchPostAndComments() {
      const id = JSON.parse(this.$route.query.id);
      if (!id) return;

      getPosts(id).then((response) => {
        this.post = response.data;
      });

      listComments({ postId: id }).then((response) => {
        console.log("评论列表:", response);
        this.comments = response.rows;
      });
    },
    submitComment() {
      if (!this.newComment.trim()) {
        this.$message.error("评论内容不能为空");
        return;
      }

      const commentData = {
        postId: this.$route.query.id,
        commentContent: this.newComment,
        userId: this.$store.state.user.id,
      };

      console.log("评论数据:", commentData);

      addComments(commentData)
        .then((response) => {
          this.$message.success("评论成功");
          this.newComment = "";
          this.fetchPostAndComments();
        })
        .catch((error) => {
          console.error("添加评论失败:", error);
          this.$message.error("评论失败，请稍后再试");
        });
    },
    deleteComment(commentId) {
      this.$confirm("确认删除这条评论吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delComments(commentId)
            .then(() => {
              this.$message.success("评论删除成功");
              this.fetchPostAndComments();
            })
            .catch((error) => {
              console.error("删除评论失败:", error);
              this.$message.error("删除评论失败，请稍后再试");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
  },
};
</script>
<style scoped>
.post-detail {
  max-width: 800px;
  margin: auto;
}
.comments-section {
  margin-top: 20px;
}
.comment-input {
  margin-bottom: 20px;
}
.comment-list {
  display: flex;
  flex-direction: column;
}
.comment {
  display: flex;
  align-items: flex-start;
  margin-top: 10px;
}
.el-avatar {
  margin-right: 10px;
}
.comment-detail {
  flex-grow: 1;
}
.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.comment-user {
  font-weight: bold;
}
.comment-time {
  font-size: 0.85rem;
  color: #999;
}
.comment-content {
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 10px;
  width: 100%;
}
</style>
